﻿using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using InfoJetSoft.Service;
using Microsoft.SharePoint;
using System.Xml;
using System.Xml.XPath;
using Microsoft.SharePoint.Utilities;
using System.Text;
using System.Web;
using ServBus.ListForm2010.Utility;
using ServBus.ListForm2010.Extension;
using FluentRibbon.Libraries;
using FluentRibbon.Definitions;
using FluentRibbon;
using Microsoft.SharePoint.WebControls;
using FluentRibbon.Definitions.Controls;
using ServBus.ListForm2010.Resources;
using System.IO;

namespace ServBus.ListForm2010.Layouts.InfoBus2010
{
    public partial class ListFormInner : LayoutsPageBase
    {
        #region Parameters

        public static bool urlMode = true;
        public static string webpartMode = string.Empty;//"NEW";
        public static string siteName;//"http://win-3ststb2hjp7";
        public static Guid webName;//"Test";
        public static string listId = "";//"test";
        public static string ctypeId = "";
        public static string itemId = "";//string.Empty;
        public static string viewId = "";//string.Empty;
        public static string infojet_ServiceAction = "/_layouts/infobus2010/xdoc.aspx";

        private static Dictionary<string, List<int>> sItemsId = new Dictionary<string, List<int>>();

        XmlNamespaceManager xNameSpace;

        static string pulishUrl = string.Empty;
        #endregion

        protected void downloadFileClick(Exception ex)
        {
            xDocViewInner.Visible = false;
            LTException.Text = ex.ToString();
            errorPanel.Visible = true;
            ErrorLog.Write("ListFormInner" + "\r\n" + Request.Url + "\r\n" + ex.Message + "\r\n" + ex.StackTrace, System.Diagnostics.EventLogEntryType.Error);

        }

        #region Page Method

        protected void Page_Load(object sender, EventArgs e)
        {
            try
            {
                InfoJetService.ServiceAction = infojet_ServiceAction;
                InfoJetSoft.Service.Util.ConfigUtil.SetEnableRichText(true);
                InfoJetSoft.Service.Util.ConfigUtil.EditRichTextOnFocus = true;
                InfoJetSoft.Service.Util.ConfigUtil.SetEnableFormFieldsCache(true);
                InfoJetSoft.Service.Util.ConfigUtil.SetEnablePlaceholderUI(true);

                webpartMode = Page.Request["wpMode"].ToUpper();
                listId = Page.Request["listId"];
                ctypeId = Page.Request["ctype"];
                //viewId = Page.Request["view"];
                siteName = SPContext.Current.Site.Url;

                webName = SPContext.Current.Web.ID;
                if (!Page.IsPostBack)
                {
                    switch (webpartMode)
                    {
                        case "NEW":
                            GenerateNewForm();
                            break;
                        case "DISP":
                            itemId = Page.Request["itemId"];
                            GenerateDisplayForm();
                            break;
                        case "EDIT":
                            itemId = Page.Request["itemId"];
                            GenerateEditForm();
                            break;
                        default:
                            break;
                    }
                }
            }
            catch (Exception ex)
            {
                downloadFileClick(ex);
            }
        }

        protected void DeleteBtn_Click(object sender, EventArgs e)
        {
            try
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(siteName))
                    {
                        using (SPWeb _web = _site.OpenWeb(webName))
                        {
                            _web.AllowUnsafeUpdates = true;
                            SPList _list = _web.Lists[new Guid(listId)];
                            int _itemId = Convert.ToInt32(itemId);
                            SPListItem _item = _list.GetItemById(_itemId);
                            _item.Recycle();
                        }
                    }
                });
                Response.Write("<script type='text/javascript'>parent.window.frameElement.commitPopup('Operation Successful!')</script>");

            }
            catch (Exception ex)
            {
                downloadFileClick(ex);
            }
        }

        protected void SaveBtn_Click(object sender, EventArgs e)
        {
            try
            {

                InfoJetContext ijCtx = new InfoJetContext();
                ijCtx.InlineFileStorage = new InlineFileStorage();
                InfoJetForm savedForm = InfoJetService.ReloadForm(Context, ijCtx);
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(savedForm.Xml);

                xNameSpace = new XmlNamespaceManager(new NameTable());
                xNameSpace.AddNamespace("my", NameSpaceConstants.MYNamespaceValue);
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(siteName))
                    {
                        using (SPWeb _web = _site.OpenWeb(webName))
                        {
                            _web.AllowUnsafeUpdates = true;
                            SPList _list = _web.Lists[new Guid(listId)];
                            int _itemId = 0;
                            if (webpartMode.Equals("NEW"))
                            {
                                SPListItem newItem = _list.Items.Add();
                                SPContentTypeId newItemContentTypeId = new SPContentTypeId(ctypeId.ToLower());
                                newItem["ContentType"] = _list.ContentTypes[newItemContentTypeId].Name;
                                newItem.Update();
                                _itemId = newItem.ID;
                            }
                            else if (webpartMode.Equals("EDIT"))
                            {
                                _itemId = Convert.ToInt32(itemId);
                            }
                            SPListItem _item = _list.GetItemById(_itemId);
                            foreach (XmlNode xNode in xDoc.ChildNodes)
                            {
                                SaveListFieldsValue(xNode, _list, _item);
                            }

                            //Lookupform
                            XmlNode subFormsNode = xDoc.SelectSingleNode("/my:myFields/my:SubForms", xNameSpace);
                            if (subFormsNode != null)
                            {
                                SaveLkpFormValue(subFormsNode, _item);
                            }
                            _item.Update();
                        }
                    }
                });
                //Response.Write("<script type='text/javascript'>window.close()</script>");
                Response.Write("<script type='text/javascript'>parent.window.frameElement.commitPopup('Operation Successful')</script>");
            }
            catch (Exception ex)
            {
                downloadFileClick(ex);
            }
        }

        #endregion

        #region Private Method

        private void GenerateDisplayForm()
        {
            sItemsId.Clear();
            string xmlTemplate = GetXMLTemplate().Xml;
            if (xmlTemplate != string.Empty)
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(xmlTemplate);

                xNameSpace = new XmlNamespaceManager(xDoc.NameTable);
                xNameSpace.AddNamespace("my", NameSpaceConstants.MYNamespaceValue);

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(siteName))
                    {
                        using (SPWeb _web = _site.OpenWeb(webName))
                        {
                            SPList _list = _web.Lists[new Guid(listId)];
                            int _itemId = Convert.ToInt32(itemId);
                            SPListItem _item = _list.GetItemById(_itemId);
                            foreach (XmlNode xNode in xDoc.ChildNodes)
                            {
                                SetListFieldsValue(xNode, _list, _item);
                            }

                            XmlNode subFormsNode = xDoc.SelectSingleNode("/my:myFields/my:SubForms", xNameSpace);
                            if (subFormsNode != null)
                            {
                                SetLkpFormValue(xDoc.CreateNavigator(), subFormsNode, _itemId);
                            }

                            InfoJetContext ijCtx = new InfoJetContext();
                            ijCtx.InlineFileStorage = new InlineFileStorage();
                            ijCtx.ExportFileStorage = new ExportFileStorage();
                            RelativeUrlResolver resolver = new RelativeUrlResolver(_xsnLocation);
                            ijCtx.RelativeUrlResolver = resolver;
                            ijCtx.IsReadonly = true;
                            if (!string.IsNullOrEmpty(viewId))
                            {
                                ijCtx.ViewName = viewId;
                            }
                            InfoJetForm editForm = InfoJetService.BuildFormByXML(Context, ijCtx, _xsnLocation, xDoc.OuterXml);

                            xDocViewInner.Text = editForm.Xhtml;
                        }
                    }
                });
            }
        }

        private void GenerateNewForm()
        {
            sItemsId.Clear();
            InfoJetForm newForm = GetXMLTemplate();

            if (newForm != null)
            {
                InfoJetContext ijCtx = new InfoJetContext();
                ijCtx.InlineFileStorage = new InlineFileStorage();
                ijCtx.ExportFileStorage = new ExportFileStorage();
                RelativeUrlResolver resolver = new RelativeUrlResolver(_xsnLocation);
                ijCtx.RelativeUrlResolver = resolver;
                if (!string.IsNullOrEmpty(viewId))
                {
                    ijCtx.ViewName = viewId;
                }
                InfoJetForm editForm = InfoJetService.BuildFormByXML(Context, ijCtx, _xsnLocation, newForm.Xml);
                xDocViewInner.Text = editForm.Xhtml;

                //this.xDocViewInner.Text = newForm.Xhtml;
            }
        }

        private void GenerateEditForm()
        {
            sItemsId.Clear();
            string xmlTemplate = GetXMLTemplate().Xml;
            if (xmlTemplate != string.Empty)
            {
                XmlDocument xDoc = new XmlDocument();
                xDoc.LoadXml(xmlTemplate);

                xNameSpace = new XmlNamespaceManager(new NameTable());
                xNameSpace.AddNamespace("my", NameSpaceConstants.MYNamespaceValue);

                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(siteName))
                    {
                        using (SPWeb _web = _site.OpenWeb(webName))
                        {
                            SPList _list = _web.Lists[new Guid(listId)];
                            int _itemId = Convert.ToInt32(itemId);
                            SPListItem _item = _list.GetItemById(_itemId);
                            foreach (XmlNode xNode in xDoc.ChildNodes)
                            {
                                SetListFieldsValue(xNode, _list, _item);
                            }
                            //Lookupform
                            XmlNode subFormsNode = xDoc.SelectSingleNode("/my:myFields/my:SubForms", xNameSpace);
                            if (subFormsNode != null)
                            {
                                SetLkpFormValue(xDoc.CreateNavigator(), subFormsNode, _itemId);
                            }

                            InfoJetContext ijCtx = new InfoJetContext();
                            ijCtx.InlineFileStorage = new InlineFileStorage();
                            ijCtx.ExportFileStorage = new ExportFileStorage();
                            RelativeUrlResolver resolver = new RelativeUrlResolver(_xsnLocation);
                            ijCtx.RelativeUrlResolver = resolver;
                            if (!string.IsNullOrEmpty(viewId))
                            {
                                ijCtx.ViewName = viewId;
                            }
                            InfoJetForm editForm = InfoJetService.BuildFormByXML(Context, ijCtx, _xsnLocation, xDoc.OuterXml);
                            xDocViewInner.Text = editForm.Xhtml;
                        }
                    }
                });
            }
        }

        private Dictionary<string, string> getViewConfigItem(SPWeb _web, string mListID, string mContentTypeID)
        {
            Dictionary<string, string> views = new Dictionary<string, string>();
            if (!string.IsNullOrEmpty(mListID) && !string.IsNullOrEmpty(mContentTypeID))
            {
                try
                {
                    SPList configList = _web.Lists[Constants.LookupForm_Config_NAME];
                    SPQuery query = new SPQuery();
                    query.Query = "<Where><And><Eq><FieldRef Name='Title' /><Value Type='Text'>" + mListID + "</Value></Eq><Eq><FieldRef Name='mContentType' /><Value Type='Text'>" + mContentTypeID + "</Value></Eq></And></Where>";
                    SPListItemCollection items = configList.GetItems(query);
                    if (items.Count > 0)
                    {
                        string dispView = Convert.ToString(items[0]["mDispView"]);
                        string editView = Convert.ToString(items[0]["mEditView"]);
                        string newView = Convert.ToString(items[0]["mNewView"]);

                        if (!string.IsNullOrEmpty(dispView))
                        {
                            views.Add("DISP", dispView);
                            views.Add("EDIT", editView);
                            views.Add("NEW", newView);
                        }

                    }
                }
                catch { }
            }
            return views;
        }


        private string _xsnLocation = "";

        private bool RegisterXSNTemplate()
        {
            Guid xsnId;

            byte[] xsnContent = null;

            bool succeed = false;
            InfoJetService.License(Constants.InfoJetLicense);

            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite _site = new SPSite(siteName))
                {
                    using (SPWeb _web = _site.OpenWeb(webName))
                    {
                        SPList _list = _web.Lists[new Guid(listId)];
                        SPContentTypeId _ctypeId = new SPContentTypeId(ctypeId.ToLower());
                        SPContentType _cType = _list.ContentTypes[_ctypeId];
                        _xsnLocation = _web.Url + "/" + _cType.ResourceFolder.Url + "/template.xsn";

                        SPFile file = _web.GetFile(_xsnLocation);
                        xsnContent = file.OpenBinary();
                        xsnId = file.UniqueId;


                        if (xsnContent == null)
                        {
                            succeed = false;
                        }
                        else
                        {
                            string md5 = CryptoUtility.ComputeMD5(xsnContent);
                            if (InfoJetService.GetMD5(_xsnLocation) == md5)
                            {
                                succeed = true;
                            }
                            else
                            {
                                InfoJetContext ijCtx = new InfoJetContext();
                                ijCtx.Variables.Add("InfoBus_XsnId", xsnId.ToString());
                                ijCtx.ResourceFileStorage = new ResourceFileStorage(_web);
                                ijCtx.InlineFileStorage = new InlineFileStorage();
                                if (!InfoJetService.RegisterWithMD5(Context, ijCtx, _xsnLocation, xsnContent, "/_layouts/infobus2010/", md5))
                                {
                                    succeed = false;
                                }
                                else
                                {
                                    succeed = true;
                                }
                            }
                        }
                        Dictionary<string, string> views = getViewConfigItem(_web, Convert.ToString(_list.ID), Convert.ToString(_cType.Id));
                        webpartMode = Page.Request["wpMode"].ToUpper();
                        if (views.ContainsKey(webpartMode))
                        {
                            viewId = views[webpartMode];
                        }
                    }
                }
            });
            return succeed;
        }

        private InfoJetForm GetXMLTemplate()
        {
            string xmlTemplate = string.Empty;
            if (RegisterXSNTemplate())
            {

                InfoJetContext ijCtx = new InfoJetContext();
                ijCtx.InlineFileStorage = new InlineFileStorage();
                ijCtx.ExportFileStorage = new ExportFileStorage();
                RelativeUrlResolver resolver = new RelativeUrlResolver(_xsnLocation);
                ijCtx.RelativeUrlResolver = resolver;
                //if (!string.IsNullOrEmpty(viewId))
                //{
                //    ijCtx.ViewName = viewId;
                //}
                InfoJetForm newForm = InfoJetService.BuildFormByTemplate(Context, _xsnLocation, ijCtx);
                return newForm;
            }
            else
            {
                return null;
            }
        }

        private void SetListFieldsValue(XmlNode xNode, SPList p_list, SPListItem p_item)
        {
            if (xNode.LocalName != "SubForms")
            {
                if (xNode.HasChildNodes)
                {
                    foreach (XmlNode cXNode in xNode.ChildNodes)
                    {
                        SetListFieldsValue(cXNode, p_list, p_item);
                    }
                }
                SetValue(xNode.CreateNavigator(), p_list, p_item);
            }
        }

        private void SetLkpFormValue(XPathNavigator rootNav, XmlNode xNode, int itemId)
        {
            //ListNode
            foreach (XmlNode listNode in xNode.ChildNodes)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(siteName))
                    {
                        using (SPWeb _web = _site.OpenWeb(webName))
                        {
                            _web.AllowUnsafeUpdates = true;
                            SPList mList = _web.Lists[new Guid(listId)];
                            string sListId = listNode.Attributes[0].Value;
                            SPList slist = _web.Lists[new Guid(sListId)];
                            XmlNode sContentTypeNode = listNode.FirstChild;
                            string sContentTypeId = sContentTypeNode.Attributes[0].Value;
                            SPContentType sContentType = slist.ContentTypes[new SPContentTypeId(sContentTypeId)];
                            SPListItemCollection resultItems = GetLKSubItems(mList, slist, itemId, sContentType.Name);
                            foreach (SPListItem sItem in resultItems)
                            {
                                XmlNode sItemNode = sContentTypeNode.Clone();
                                XPathNavigator sItemNav = sItemNode.CreateNavigator();
                                //sItemNav.CreateAttribute("", "ItemID", "", sItem.ID.ToString());
                                sItemNode.Attributes["my:Item_ID"].Value = sItem.ID.ToString();

                                foreach (XmlNode sFieldNode in sItemNode.ChildNodes)
                                {
                                    SetValue(sFieldNode.CreateNavigator(), slist, sItem);
                                }

                                XPathNavigator listNav = rootNav.SelectSingleNode(string.Format("/my:myFields/my:SubForms/my:{0}", listNode.LocalName), xNameSpace);
                                listNav.AppendChild(sItemNav);
                            }
                            listNode.RemoveChild(sContentTypeNode);
                        }
                    }
                });
            }
        }

        private SPListItemCollection GetLKSubItems(SPList mList, SPList sList, int itemId, string ctName)
        {
            SPListItemCollection resultItems = null;

            SPField lkpField = GetLKPField(mList, sList);

            if (!string.IsNullOrEmpty(lkpField.Title))
            {
                SPQuery query = new SPQuery();
                query.Query = string.Format("<Where><And><Eq><FieldRef Name='{0}' LookupId='TRUE' />" +
                                       "<Value Type='Lookup'>{1}</Value></Eq><Eq><FieldRef Name='ContentType' /><Value Type='Text'>{2}</Value></Eq></And></Where>", lkpField.InternalName, itemId,ctName);
                resultItems = sList.GetItems(query);
                if (!sItemsId.ContainsKey(sList.Title))
                {
                    resultItems = sList.GetItems(query);
                    List<int> itemIds = new List<int>();
                    foreach (SPListItem item in resultItems)
                    {
                        itemIds.Add(item.ID);
                    }
                    sItemsId.Add(sList.Title, itemIds);
                }
            }
            return resultItems;
        }

        private SPField GetLKPField(SPList mList, SPList sList)
        {
            SPField lkpField = null;
            //Find lkp Field
            foreach (SPField sField in sList.Fields)
            {
                if (sField.Type.Equals(SPFieldType.Lookup))
                {
                    SPFieldLookup sLKPField = (SPFieldLookup)sField;
                    Guid sLKPID = new Guid(sLKPField.LookupList);
                    if (sLKPID.Equals(mList.ID))
                    {
                        lkpField = sLKPField;
                        break;
                    }
                }
            }

            return lkpField;
        }

        private void SetValue(XPathNavigator p_xPathNav, SPList p_list, SPListItem p_item)
        {
            string m_field_internal_name = string.Empty;
            string m_field_value = string.Empty;

            if (p_xPathNav != null)
            {
                string localName = Convert.ToString(p_xPathNav.LocalName);

                //begin looping through the nodes
                if (localName != null)
                {
                    #region Set Value

                    m_field_internal_name = p_xPathNav.LocalName;
                    if (p_list.Fields.ContainsField(m_field_internal_name))
                    {
                        SPField m_field = p_list.Fields.GetField(m_field_internal_name);

                        m_field_value = GetFormValueFromField(m_field, p_item);

                        if (string.IsNullOrEmpty(m_field_value))
                        {
                            return;
                        }

                        //根据不同的Field类型，表单对应不同的数据类型，这里需要判断
                        switch (m_field.Type)
                        {
                            case SPFieldType.Number:
                                DeleteNil(p_xPathNav);
                                p_xPathNav.SetValue(m_field_value);
                                break;

                            case SPFieldType.DateTime:
                                DeleteNil(p_xPathNav);
                                SPFieldDateTime dateTimeField = (SPFieldDateTime)m_field;
                                //DateOnly
                                if (dateTimeField.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
                                {
                                    DateTime dt = DateTime.Parse(m_field_value);
                                    p_xPathNav.SetValue(dt.Date.ToString("yyyy-MM-dd"));
                                }
                                else
                                {
                                    p_xPathNav.SetValue(m_field_value);
                                }
                                break;

                            case SPFieldType.User:
                                //if (p_xPathNav.InnerXml == "")
                                //{
                                //    return;
                                //}
                                InsertToUserType(p_item, m_field.Title, p_xPathNav);
                                break;

                            case SPFieldType.MultiChoice:
                                InsertIntoCheckBoxType(m_field_value, p_xPathNav, p_xPathNav.Name);
                                break;

                            case SPFieldType.Note:
                                p_xPathNav.InnerXml = m_field_value;
                                break;
                            case SPFieldType.Lookup:
                                p_xPathNav.SetValue(m_field_value);
                                break;

                            default:
                                p_xPathNav.SetValue(m_field_value);
                                break;
                        }
                    }
                    #endregion
                }
            }
        }

        private void SaveListFieldsValue(XmlNode xNode, SPList p_list, SPListItem p_item)
        {
            if (xNode.LocalName != "SubForms")
            {
                if (xNode.HasChildNodes)
                {
                    foreach (XmlNode cXNode in xNode.ChildNodes)
                    {
                        SaveListFieldsValue(cXNode, p_list, p_item);
                    }
                }
                SaveValue(xNode.CreateNavigator(), p_list, p_item);
            }
        }

        private void SaveLkpFormValue(XmlNode xNode, SPListItem _item)
        {
            //ListNode
            foreach (XmlNode listNode in xNode.ChildNodes)
            {
                SPSecurity.RunWithElevatedPrivileges(delegate()
                {
                    using (SPSite _site = new SPSite(siteName))
                    {
                        using (SPWeb _web = _site.OpenWeb(webName))
                        {
                            _web.AllowUnsafeUpdates = true;
                            SPList mList = _web.Lists[new Guid(listId)];
                            string sListId = listNode.Attributes[0].Value;
                            SPList slist = _web.Lists[new Guid(sListId)];
                            XmlNode sContentTypeNode = listNode.FirstChild;
                            string sContentTypeId = sContentTypeNode.Attributes[0].Value;
                            SPContentType sContentType = slist.ContentTypes[new SPContentTypeId(sContentTypeId)];

                            SPField lkpField = GetLKPField(mList, slist);
                            List<int> itemIds = new List<int>();
                            if (sItemsId.ContainsKey(slist.Title))
                            {
                                itemIds = sItemsId[slist.Title];
                            }
                            foreach (XmlNode sItemNode in listNode.ChildNodes)
                            {
                                if (webpartMode.Equals("NEW"))
                                {
                                    if (!string.IsNullOrEmpty(sItemNode.FirstChild.InnerXml))
                                    {
                                        SPListItem newItem = slist.Items.Add();
                                        newItem["ContentType"] = sContentType.Name;
                                        newItem.Update();
                                        foreach (XmlNode sFieldNode in sItemNode.ChildNodes)
                                        {
                                            SaveValue(sFieldNode.CreateNavigator(), slist, newItem);
                                        }
                                        newItem[lkpField.Title] = new SPFieldLookupValue(_item.ID, _item.Title);
                                        newItem.Update();
                                    }
                                }
                                else if (webpartMode.Equals("EDIT"))
                                {
                                    XmlAttribute sItemIDAttr = sItemNode.Attributes["my:Item_ID"];
                                    if (sItemIDAttr != null)
                                    {
                                        int _itemId = Convert.ToInt32(sItemIDAttr.Value);
                                        SPListItem editItem = slist.GetItemById(_itemId);

                                        foreach (XmlNode sFieldNode in sItemNode.ChildNodes)
                                        {
                                            SaveValue(sFieldNode.CreateNavigator(), slist, editItem);
                                        }
                                        editItem[lkpField.Title] = new SPFieldLookupValue(_item.ID, _item.Title);
                                        editItem.Update();

                                        if (itemIds.Contains(_itemId))
                                        {
                                            itemIds.Remove(_itemId);
                                        }
                                    }
                                    else
                                    {
                                        SPListItem newItem = slist.Items.Add();
                                        newItem["ContentType"] = sContentType.Name;
                                        newItem.Update();
                                        foreach (XmlNode sFieldNode in sItemNode.ChildNodes)
                                        {
                                            SaveValue(sFieldNode.CreateNavigator(), slist, newItem);
                                        }

                                        newItem[lkpField.Title] = new SPFieldLookupValue(_item.ID, _item.Title);
                                        newItem.Update();
                                    }
                                }
                            }

                            foreach (int delItemId in itemIds)
                            {
                                slist.Items.DeleteItemById(delItemId);
                            }
                        }
                    }
                });
            }
        }

        private void SaveValue(XPathNavigator p_xPathNav, SPList p_list, SPListItem p_item)
        {
            string m_field_internal_name = string.Empty;

            if (p_xPathNav != null)
            {
                string localName = Convert.ToString(p_xPathNav.LocalName);

                //begin looping through the nodes
                if (localName != null && localName != "ID")
                {
                    m_field_internal_name = p_xPathNav.LocalName;
                    if (p_list.Fields.ContainsField(m_field_internal_name))
                    {
                        SPField m_field = p_list.Fields.GetField(m_field_internal_name);
                        SPFieldType m_field_type = m_field.Type;
                        //单独处理CheckBox
                        if (m_field_type.Equals(SPFieldType.Boolean))
                        {
                            if (!string.IsNullOrEmpty(p_xPathNav.Value))
                            {
                                p_item[m_field.Id] = Convert.ToBoolean(p_xPathNav.Value);
                            }
                            else
                            {
                                p_item[m_field.Id] = false;
                            }
                            p_item.Update();
                        }
                        else if (!string.IsNullOrEmpty(p_xPathNav.Value))
                        {
                            if (m_field_type.Equals(SPFieldType.MultiChoice))
                            {
                                if (p_xPathNav.MoveToFirstChild())
                                {
                                    SPFieldMultiChoiceValue values = new SPFieldMultiChoiceValue();
                                    do
                                    {
                                        string fieldvalue = p_xPathNav.Value;
                                        if (!string.IsNullOrEmpty(fieldvalue))
                                        {
                                            values.Add(fieldvalue);
                                        }
                                    }
                                    while (p_xPathNav.MoveToNext());
                                    p_item[m_field.Id] = values;
                                    p_item.Update();
                                }
                            }
                            else if (m_field_type.Equals(SPFieldType.Note))
                            {
                                object m_field_value = GetFieldValueByType(m_field_type, p_xPathNav.InnerXml);
                                p_item[m_field.Id] = m_field_value;
                                p_item.Update();
                            }
                            else if (m_field_type.Equals(SPFieldType.User))
                            {
                                xNameSpace.AddNamespace("pc", "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");
                                SPFieldUserValueCollection uvc = new SPFieldUserValueCollection();
                                if (p_xPathNav.HasChildren)
                                {
                                    SPSecurity.RunWithElevatedPrivileges(delegate()
                                    {
                                        using (SPSite _site = new SPSite(siteName))
                                        {
                                            using (SPWeb _web = _site.OpenWeb(webName))
                                            {
                                                p_xPathNav.MoveToFirstChild();
                                                do
                                                {
                                                    XPathNavigator nav = p_xPathNav.SelectSingleNode("./pc:AccountId", xNameSpace);
                                                    SPUser user = (SPUser)GetFieldValueByType(m_field_type, nav.Value);
                                                    uvc.Add(new SPFieldUserValue(_web, user.ID, user.Name));
                                                }
                                                while (p_xPathNav.MoveToNext());
                                            }
                                        }
                                    });
                                    p_item[m_field.Id] = uvc;
                                    p_item.Update();
                                }
                                else
                                {
                                    p_item[m_field.Id] = "";
                                    p_item.Update();
                                }
                                //XPathNavigator nav = p_xPathNav.SelectSingleNode("./pc:Person/pc:AccountId", xNameSpace);
                                //while (nav.MoveToFirstChild())
                                //{
                                //    //p_xPathNav.MoveToChild("AccountId", "http://schemas.microsoft.com/office/infopath/2007/PartnerControls");
                                //    object m_field_value = GetFieldValueByType(m_field_type, nav.Value);
                                //    p_item[m_field.Id] = m_field_value;
                                //    p_item.Update();
                                //}
                            }
                            else
                            {
                                object m_field_value = GetFieldValueByType(m_field_type, p_xPathNav.Value);
                                p_item[m_field.Id] = m_field_value;
                                p_item.Update();
                            }
                        }
                    }
                }
            }
        }

        //通过SPField的Type，返回不同的对象，给Item的属性赋值。
        public object GetFieldValueByType(SPFieldType p_field_type, string p_str_value)
        {
            object m_field_value = null;
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite _site = new SPSite(siteName))
                {
                    using (SPWeb _web = _site.OpenWeb(webName))
                    {
                        _web.AllowUnsafeUpdates = true;
                        switch (p_field_type)
                        {
                            case SPFieldType.Text:
                                m_field_value = p_str_value;
                                break;
                            case SPFieldType.User:
                                try
                                {
                                    SPUser m_user = _web.EnsureUser(p_str_value);
                                    m_field_value = m_user;
                                }
                                catch (Exception ex)
                                {
                                    //Console.WriteLine(ex.ToString());
                                    //m_field_value = _web.CurrentUser;
                                    //输出错误信息，用户不存在之类的。
                                }
                                break;
                            case SPFieldType.Integer:
                                int m_integer = int.Parse(p_str_value);
                                m_field_value = m_integer;
                                break;
                            case SPFieldType.Number:
                                double m_number = double.Parse(p_str_value);
                                m_field_value = m_number;
                                break;
                            case SPFieldType.Lookup:
                                SPFieldLookupValue m_lookup_value = new SPFieldLookupValue(p_str_value);
                                m_field_value = m_lookup_value;
                                break;
                            case SPFieldType.Boolean:
                                m_field_value = Convert.ToBoolean(p_str_value);
                                break;
                            case SPFieldType.Note:
                                string m_string = Convert.ToString(p_str_value);
                                m_string = formatXhtmlString(m_string);
                                m_field_value = m_string;
                                break;
                            default:
                                m_field_value = p_str_value;
                                break;
                        }
                    }
                }
            });

            return m_field_value;
        }

        private string formatXhtmlString(string m_string)
        {
            while (m_string.Contains("/>"))
            {
                int firstIndex = m_string.IndexOf("/>");
                string sub_m_string = m_string.Substring(0, firstIndex);
                string sub_m_string_later = m_string.Substring(firstIndex + 2);
                int lastIndex = sub_m_string.LastIndexOf("<") + 1;
                int spaceIndex = sub_m_string.IndexOf(" ", lastIndex);
                string tagName = sub_m_string.Substring(lastIndex, spaceIndex - lastIndex);
                sub_m_string = sub_m_string + "></" + tagName + ">";
                m_string = sub_m_string + sub_m_string_later;

            }
            //m_string = m_string.Replace("\r\n", "<BR>");
            return m_string;
        }
        /// <summary>
        /// 从列表的Field中获取值填充到InfoPath节点中
        /// </summary>
        /// <param name="p_field"></param>
        /// <param name="p_item"></param>
        /// <returns></returns>
        private string GetFormValueFromField(SPField p_field, SPListItem p_item)
        {

            string m_str_value = string.Empty;
            try
            {

                if (p_item[p_field.Id] == null)
                {
                    return m_str_value;
                }
            }
            catch (Exception ex)
            {
                return m_str_value;
            }


            switch (p_field.Type)
            {
                case SPFieldType.Lookup:
                    string m_lookup_value = p_item[p_field.Id].ToString();

                    int t_index = m_lookup_value.IndexOf("#");
                    m_str_value = m_lookup_value.Substring(0, t_index - 1);
                    //m_str_value = m_lookup_value;                   //读取数据时出错。TO DO...目前先临时改回来
                    break;

                case SPFieldType.DateTime:
                    DateTime m_time = (DateTime)p_item[p_field.Id];
                    m_str_value = XmlConvert.ToString(m_time);
                    break;

                case SPFieldType.Note:
                    //Obsolete

                    m_str_value = Convert.ToString(p_item[p_field.Id]);
                    m_str_value = GetMulitTextString(m_str_value);
                    break;

                case SPFieldType.URL:
                    SPFieldUrlValue urlValue = new SPFieldUrlValue(Convert.ToString(p_item[p_field.Id]));
                    m_str_value = urlValue.Url;
                    break;

                case SPFieldType.Boolean:
                    bool booleanField = Convert.ToBoolean(p_item[p_field.Id]);
                    if (booleanField)
                    {
                        m_str_value = "true";
                    }
                    else
                    {
                        m_str_value = "false";
                    }
                    break;

                default:
                    m_str_value = Convert.ToString(p_item[p_field.Id]);
                    break;
            }
            return m_str_value;
        }

        /// <summary>
        /// 架构验证发现无数据类型错误的解决方案，目前只用于数字类型
        /// </summary>
        /// <param name="node">当前节点</param>
        private void DeleteNil(XPathNavigator node)
        {
            if (node.MoveToAttribute("nil", "http://www.w3.org/2001/XMLSchema-instance"))
            {
                node.DeleteSelf();
            }
        }

        /// <summary>
        /// 插入用户信息到pc:Person类型的节点中
        /// </summary>
        /// <param name="fieldValue"></param>
        /// <param name="xPathNav"></param>
        private void InsertToUserType(SPListItem item, string fieldTitle, XPathNavigator xPathNav)
        {
            string pcValue = "";
            if (xPathNav.HasChildren)
            {
                xPathNav.SetValue("");
            }
            SPSecurity.RunWithElevatedPrivileges(delegate()
            {
                using (SPSite _site = new SPSite(siteName))
                {
                    using (SPWeb _web = _site.OpenWeb(webName))
                    {
                        try
                        {
                            SPFieldUser _user = (SPFieldUser)item.Fields[fieldTitle];
                            SPFieldUserValue userValue = (SPFieldUserValue)_user.GetFieldValue(Convert.ToString(item[fieldTitle]));
                            SPUser user = userValue.User;
                            pcValue = "<pc:Person><pc:DisplayName>" + user.Name + "</pc:DisplayName><pc:AccountId>" + user.LoginName + "</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person>";
                            xPathNav.AppendChild(pcValue);

                        }
                        catch
                        {
                            SPFieldUserValueCollection Values = item[fieldTitle] as SPFieldUserValueCollection;

                            foreach (SPFieldUserValue Value in Values)
                            {
                                SPUser User = Value.User;
                                if (User != null)
                                {
                                    pcValue = "<pc:Person><pc:DisplayName>" + User.Name + "</pc:DisplayName><pc:AccountId>" + User.LoginName + "</pc:AccountId><pc:AccountType>User</pc:AccountType></pc:Person>";
                                    xPathNav.AppendChild(pcValue);
                                }
                                else
                                {
                                    SPGroup Group = Web.Groups.GetByID(Value.LookupId);
                                    pcValue = "<pc:Person><pc:DisplayName>" + Group.Name + "</pc:DisplayName><pc:AccountId>" + Group.LoginName + "</pc:AccountId><pc:AccountType>Group</pc:AccountType></pc:Person>";
                                    xPathNav.AppendChild(pcValue);
                                }
                            }
                        }
                    }
                }
            });

        }

        private void InsertIntoCheckBoxType(string fieldValue, XPathNavigator xPathNav, string fieldName)
        {
            fieldName = fieldName + "_1";
            SPFieldMultiChoiceValue choiceValue = new SPFieldMultiChoiceValue(fieldValue);

            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < choiceValue.Count; i++)
            {
                sb.Append("<" + fieldName + ">").Append(choiceValue[i]).Append("</" + fieldName + ">");
            }
            xPathNav.InnerXml = sb.ToString();
        }
        
        private string GetMulitTextString(string p_field_string)
        {
            string m_comment = string.Empty;
            try
            {

                XmlDocument m_doc = new XmlDocument();
                m_doc.LoadXml(p_field_string);

                m_comment = "<div xmlns=\"http://www.w3.org/1999/xhtml\">" + m_doc.InnerXml + "</div>";

            }
            catch (Exception mm)
            {
                m_comment = "<div xmlns=\"http://www.w3.org/1999/xhtml\">" + p_field_string + "</div>";

            }

            return m_comment;
        }
        
        #endregion
    }
}
